import React, { useEffect, useState } from "react";
import axios from "axios";
import QTtoST from "../QueryTexttoSpeechTask/index.jsx";
export default function App(props) {
  const { text } = props;
  const [aitext, setText] = useState("");
  const AK = "fUOXAR0kdDSGnlxNbiObftwT";
  const SK = "YrwdRy0LcxruhKkRGIttFLMcsKeScYd3";
  //获取子组件传递的值 text
  // const texts=props.text()

  async function main() {
    var options = {
      method: "POST",
      url: "/baidu/tts/v1/create?access_token=" + (await getAccessToken()),
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json",
      },
      data: JSON.stringify({
        text: text,
        format: "mp3-16k",
        voice: 0,
        lang: "zh",
        speed: 5,
        pitch: 5,
        volume: 5,
        enable_subtitle: 0,
      }),
    };

    axios(options)
      .then((response) => {
        console.log(response.data.task_id);
        // setText(response.data.task_id)
        async function main() {
          var options = {
            method: "POST",
            url: "/baidu/tts/v1/query?access_token=" + (await getAccessToken()),
            headers: {
              "Content-Type": "application/json",
              Accept: "application/json",
            },
            data: JSON.stringify({
              task_ids: [response.data.task_id],
            }),
          };

          axios(options)
            .then((response) => {
              console.log(response.data.tasks_info[0].task_status);
              if (response.data.tasks_info[0].task_status == "Running") {
                setTimeout(() => {
                  main();
                }, 1000);
              } else {
                console.log(
                  response.data.tasks_info[0].task_result.speech_url
                );
                setText(response.data.tasks_info[0].task_result.speech_url)

              }
            })
            .catch((error) => {
              throw new Error(error);
            });
        }
        main();
      })
      .catch((error) => {
        throw new Error(error);
      });
  }

  /**
   * 使用 AK，SK 生成鉴权签名（Access Token）
   * @return string 鉴权签名信息（Access Token）
   */
  function getAccessToken() {
    let options = {
      method: "POST",
      url:
        "/baidutok/token?grant_type=client_credentials&client_id=" +
        AK +
        "&client_secret=" +
        SK,
    };
    return new Promise((resolve, reject) => {
      axios(options)
        .then((res) => {
          resolve(res.data.access_token);
        })
        .catch((error) => {
          reject(error);
        });
    });
  }
  useEffect(() => {
    main();
    return () => {
      // setText("");
    };
  }, [text]);
  return <div>
     <QTtoST src={aitext} />
     </div>;
}
